﻿#include "serialportrequester.h"
#include "widgetserialportcfg.h"

SerialPortRequester::SerialPortRequester(QObject *parent) : BaseRequester(parent)
{
    m_serialPort=new QSerialPort(this);
    m_wrap=new SerialPortWrap(this);
    m_wrap->setSerialPort(m_serialPort);
}

SerialPortRequester::~SerialPortRequester()
{

}

bool SerialPortRequester::connectToHost()
{
    QJsonObject tobj={
        {"address","COM1"},
        {"baud_rate",9600},
        {"data_bits","Data6"},
        {"stop_bits","OneStop"},
        {"parity","NoPraity"}
    };

    _obj=tobj;

    QMap<QString,QSerialPort::Parity> parityMap=SerialPortWrap::getParityMap();
    QMap<QString,QSerialPort::DataBits> dataMap=SerialPortWrap::getDataMap();
    QMap<QString,QSerialPort::StopBits> stopMap=SerialPortWrap::getStopMap();
    m_serialPort->setPortName(_obj["address"].toString());
    m_serialPort->setBaudRate(_obj["baud_rate"].toInt());
    m_serialPort->setDataBits(dataMap[_obj["data_bits"].toString()]);
    m_serialPort->setStopBits(stopMap[_obj["stop_bits"].toString()]);
    m_serialPort->setParity(parityMap[_obj["parity"].toString()]);
    m_serialPort->setFlowControl(QSerialPort::NoFlowControl);  //无流控制
    m_serialPort->setReadBufferSize(1000);

    return m_serialPort->open(QIODevice::ReadWrite);
}

bool SerialPortRequester::isConnected()
{
    return m_serialPort->isOpen();
}

bool SerialPortRequester::disConnect()
{
    m_serialPort->close();
    return true;
}

QByteArray SerialPortRequester::request(QByteArray data)
{
    QByteArray rec;
    m_wrap->sendReply(data,rec);
    return rec;
}

bool SerialPortRequester::requestNoReply(QByteArray data)
{
    return m_wrap->sendNoReply(data);
}

QWidget *SerialPortRequester::getConfigWidget()
{
    WidgetSerialPortCfg *cfg=new WidgetSerialPortCfg();
    cfg->setComm(this);
    return cfg;
}
